package cn.zhikaizhang.indexview;

import android.content.Context;
import android.graphics.Paint;
import android.util.TypedValue;
import com.ecity.android.tinypinyin.Pinyin;

public class PinYinUtil {

  /**
   * convert dp to px
   */
  public static int dp2px(Context context, float dp) {
    return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
        context.getResources().getDisplayMetrics());
  }

  /**
   * get the baseline to draw text between top and bottom
   */
  public static float getBaseline(float top, float bottom, Paint paint) {
    Paint.FontMetrics fontMetrics = paint.getFontMetrics();
    return (top + bottom - fontMetrics.bottom - fontMetrics.top) / 2;
  }

  /**
   * 将String转化为每个字的首字母，如北京-BEIJING
   */
  public static String toPinyin(String str) {
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < str.length(); i++) {
      // 这里要统一转成大写，排序比较的时候用
      sb.append(Pinyin.toPinyin(str.charAt(i)).toUpperCase());
    }
    return sb.toString();
  }

  /**
   * 将String转化为每个字的首字母，如北京-BJ
   */
  public static String toJianPin(String character) {
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < character.length(); i++) {
      sb.append(Pinyin.toPinyin(character.charAt(i)).toUpperCase().charAt(0));
    }
    return sb.toString();
  }

  /**
   * get the index of a string
   */
  public static char getIndex(String src) {
    String res = toPinyin(src);
    if (res.charAt(0) >= 'A' && res.charAt(0) <= 'Z') {
      return res.charAt(0);
    } else {
      return '#';
    }
  }
}
